def toBuilderLines( node, indent = false ){
    def lines = []
    
    def children = node."*"
    if(children.isEmpty() ){
        lines << "${node.name()}()"
    }
    else if( children.size() == 1 && children[0] instanceof String ){
        lines << "${node.name()}(${children[0]})"
    } else{
        lines << "${node.name()}(${node.attributes().collect{ it.key + ':' + it.value }.join('')}){"
            node."*".findAll{ !(it instanceof String) }.each{
                lines += toBuilderLines(it, true)
            }
            lines << "}"
    }
    
    lines = lines.collect{ (indent?" "*4:"") + it }
}

textArea.with{
    def selection = selection[0].clone()
    def root = new XmlParser().parseText(selectedText)
    
    selectedText = toBuilderLines(root).join("\n")
    //addToSelection(new org.gjt.sp.jedit.textarea.Selection.Range(selection.start, selection.end + up))
}
